package com.dm0858.bianmin.mine.base;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.dm0858.bianmin.R;

import java.util.ArrayList;
import java.util.List;


/**
 * @description Activity的基类
 * @author 迪迪丶Sir
 * @e-mail asd969709719@qq.com
 * @since 2020-03-17
 **/
public abstract class BaseActivity extends AppCompatActivity {


    private static Context context;
    private Intent intent;



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BaseAtyContainer.getInstance().addActivity(this);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        context = this;
    }



    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 结束Activity&从栈中移除该Activity
        BaseAtyContainer.getInstance().removeActivity(this);
    }

    /**
     * 子类通过继承可直接调用权限工具类
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        PermissionUtils.onRequestPermissionResult(this,requestCode,permissions,grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode){
            case KeyEvent.KEYCODE_BACK:
                onBackPressed();
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * @description 启动新的Activity
     * @param
     * @return
     * @author 迪迪丶Si
     * @since 2020-03-18
     **/
    public void startActivity(Class<?> cls) {
        startActivity(cls,null);
    }

    /**
     * @description 启动新的Activity
     * @param
     * @return
     * @author 迪迪丶Si
     * @since 2020-03-18
     **/
    public void startActivity(Class<?> cls, boolean isFinish) {
        startActivity(cls,null,isFinish);
    }

    /**
     * @methodName
     * @description 启动新的Activity
     * @param  cls 需要启动的Activity
     * @param bundle 需要传递的数据
     * @return
     * @author 迪迪丶Sir
     * @since 2020-03-15
     **/
    public void startActivity(Class<?> cls, @Nullable Bundle bundle){
        intent = new Intent(this,cls);
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        if (bundle != null) intent.putExtras(bundle);
        startActivity(intent);
    }

    /**
     * @methodName
     * @description 启动新的Activity
     * @param  cls 需要启动的Activity
     * @param bundle 需要传递的数据
     * @return
     * @author 迪迪丶Sir
     * @since 2020-03-15
     **/
    public void startActivity(Class<?> cls, @Nullable Bundle bundle, boolean isFinish){
        intent = new Intent(this,cls);
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        if (bundle != null) intent.putExtras(bundle);
        startActivity(intent);
        if (isFinish) onBackPressed();
    }


    /**
     * @description 吐司
     * @param
     * @return
     * @author 迪迪丶Sir
     * @since 2020-03-18
     **/
    protected void Toast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();;
    }

    /**
     * @description 用于初始化一些视图
     * @param
     * @return
     * @author 迪迪丶Sir
     * @since 2020-03-16
     **/
    protected abstract void initView();

    /**
     * @description 处理一些逻辑
     * @param
     * @return
     * @author 迪迪丶Sir
     * @since 2020-03-16
     **/
    protected abstract void initData();


    /**
     * @param
     * @return
     * @description 通过拦截点击事件判断隐藏软键盘
     * @author 迪迪丶Sir
     * @since 2020-03-17
     **/
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
//            if (isShouldHideKeyboard(v, ev))
//                KeyboardUtils.hideSoftInput(this);
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * @param
     * @return
     * @description 是否应该隐藏键盘
     * @author 迪迪丶Sir
     * @since 2020-03-17
     **/
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if ((v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationOnScreen(l);
            int left = l[0],
                    top = l[1],
                    right = left + v.getWidth(),
                    bottom = top + v.getHeight();
            return !(event.getRawX() > left && event.getRawX() < right &&
                    event.getRawY() > top && event.getRawY() < bottom);
        }
        return false;
    }

    /**
     * @description 用来收集各个activity，方便直接clean
     * @author 迪迪丶Sir
     * @e-mail asd969709719@qq.com
     * @since 2020-04-03
     **/
    public static class BaseAtyContainer {

        private BaseAtyContainer() {

        }

        private static BaseAtyContainer instance = new BaseAtyContainer();
        private static List<Activity> activityStack = new ArrayList<Activity>();

        public static BaseAtyContainer getInstance() {
            return instance;
        }

        public static Context getContext() { return context; }

        public List<Activity> getActivityStack() {
            return activityStack;
        }

        public void addActivity(Activity aty) {
            activityStack.add(aty);
        }

        public void removeActivity(Activity aty) {
            activityStack.remove(aty);
        }


        /**
         * 结束所有Activity
         */
        public void finishAllActivity() {
            for (int i = 0, size = activityStack.size(); i < size; i++) {
                if (null != activityStack.get(i)) {
                    activityStack.get(i).finish();
                }
            }
            activityStack.clear();
        }

        /**
         * @description kill掉app
         * @param
         * @return
         * @author 迪迪丶Sir
         * @since 2020-04-07
         **/
        public void killApp(){
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }

    /**
     * @description 将当前activity之下的activity全部finish
     * @param
     * @return
     * @author 迪迪丶Sir
     * @since 2020-04-07
     **/
    public void killActivityExceptTop() {
        List<Activity> activityList = BaseAtyContainer.getInstance().getActivityStack();
        int len = activityList.size() - 1;
        for (int i = 0;i < len;i++ ){
            activityList.get(i).finish();
        }
    }

//    /**
//     * @description 电话权限
//     * @param
//     * @return
//     * @author 迪迪丶Sir
//     * @since 2020-03-29
//     **/
//    public void requestPermission(String permission, RequestPermissionListener listener) {
//        PermissionUtils.requestPermissions(
//                this,
//                1,
//                PermissionConstants.getPermission(permission),
//                new PermissionUtils.OnPermissionListener() {
//                    @Override
//                    public void onPermissionGranted() {
//                        listener.onSuccess();
//                    }
//                    @Override
//                    public void onPermissionDenied(final String[] deniedPermissions, boolean alwaysDenied) {
//                        if (alwaysDenied) {
//                            DialogUtils.showPermissionManagerDialog(BaseActivity.this, PermissionConstants.getPermissionName(permission));
//                        } else {
//                            new AlertDialog.Builder(BaseActivity.this)
//                                    .setTitle("温馨提示")
//                                    .setMessage("拒绝此权限可能会影响软件的使用")
//                                    .setNegativeButton("取消", (dialogInterface, i) -> {
//                                    })
//                                    .setPositiveButton("验证权限", (dialogInterface, i) -> PermissionUtils.requestPermissionsAgain(BaseActivity.this, deniedPermissions, 1))
//                                    .show();
//
//                        }
//                    }
//                });
//    }

    public interface RequestPermissionListener{
        void onSuccess();
    }

    /**
     * @description 拨打电话
     * @param
     * @return
     * @author 迪迪丶Sir
     * @since 2020-03-29
     **/
    public void callPhone(String phoneNum) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phoneNum);
        intent.setData(data);
        startActivity(intent);
    }


}
